from django.db import models

from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import UserManager

# Create your models here.


class CustomUserManager(UserManager):
    use_in_migrations = True

    def _create_user(self, name, password, **extra_fields):
        """
        Create and save a user with the given name, and password.
        """
        if not name:
            raise ValueError('The given name must be set')
        user = self.model(name=name, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, name, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(name, password, **extra_fields)

    def create_superuser(self, name, password, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(name, password, **extra_fields)


class Account(models.Model):
    """BitMex 账号
    """

    name = models.CharField(
        'BitMex账号名', max_length=100,
        help_text='请使用真实的帐号名或邮箱！')
    api_key = models.CharField('API Key', max_length=250,
                               blank=True, null=True)
    api_secret = models.CharField('API Secret', max_length=250,
                                  blank=True, null=True)
    description = models.CharField('描述', max_length=256,
                                   blank=True, null=True)
    create_at = models.DateTimeField('创建时间', auto_now_add=True)

    is_testnet = models.BooleanField(
        _('是否测试网账号'),
        default=True,
        help_text=_('是否BitMex testnet 账号'),
    )


    class Meta:
        verbose_name = 'BitMex账号'
        verbose_name_plural = 'BitMex账号'

    def __str__(self):
        return self.name


class User(AbstractBaseUser, PermissionsMixin):
    account = models.ForeignKey(
        Account, models.SET_NULL, null=True, blank=True, verbose_name='所属交易帐号')
    name = models.CharField('登录名', max_length=30, unique=True)
    nickname = models.CharField('姓名', max_length=30, null=True, blank=True)
    mobile = models.CharField('手机', max_length=11)
    email = models.EmailField('邮箱', blank=True, null=True)

    objects = CustomUserManager()

    is_staff = models.BooleanField(
        _('staff status'),
        default=False,
        help_text=_('Designates whether the user can log into this admin site.'),
    )

    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_(
            'Designates whether this user should be treated as active. '
            'Unselect this instead of deleting accounts.'
        ),
    )

    EMAIL_FIELD = 'email'
    USERNAME_FIELD = 'name'
    REQUIRED_FIELDS = ['mobile']

    class Meta:
        verbose_name = '交易员'
        verbose_name_plural = '交易员'

    def clean(self):
        super().clean()
        self.email = self.__class__.objects.normalize_email(self.email)

    def get_full_name(self):
        return self.name

    def get_short_name(self):
        return self.name

    def __str__(self):
        return self.name


